import React, {FC, useRef} from "react";

import axios from "axios";

import Button from "../Button/button";

export interface uploadProps {
  action: string,
  onProgress?: (percentage: number, file: File) => void
  onSuccess?: (data: any, file: File) => void
  onError?: (err: any, file: File) => void
}

const Upload: FC<uploadProps> = (props) => {
  const {action, onProgress, onError, onSuccess} = props

  const fileInput = useRef<HTMLInputElement>(null);
  const handleClick = () => {
    if (fileInput.current) {
      fileInput.current.click();
    }
  }
  const fileInputOnChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files) {
      return
    }
    uploadFiles(files)
  }

  const uploadFiles = (fileList: FileList) => {
    let postFiles = Array.from(fileList);
    postFiles.forEach(file => {
      const formData = new FormData();
      formData.append(file.name, file);
      axios.post('https://www.mocky.io/v2/5cc8019d300000980a055e76', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: (e) => {
          let percentage = Math.round((e.loaded) * 100 / e.total) || 0;
          console.log(percentage)
          if (onProgress) {
            onProgress(percentage, file)
          }
        }
      }).then(resp => {
        console.log(resp);
        if (onSuccess) {
          onSuccess(resp, file)
        }
      }).catch(err => {
        console.log(err);
        if (onError) {
          onError(err, file)
        }
      })
    })
  }
  return (
    <div className="">
      <Button btnType="primary" onClick={handleClick}> Upload File</Button>
      <input
        onChange={fileInputOnChange}
        ref={fileInput}
        className="viking-file-input"
        style={{display: "none"}}
        type="file"/>
    </div>
  )
}

export default Upload;